import * as THREE from 'three';
import { Line2, LineGeometry, LineMaterial } from 'three/examples/jsm/Addons.js';
import { IntervalTime } from '.';
import { ResourceTracker } from './ResourceTracker';
import { Group } from '@tweenjs/tween.js';

// 用于存储线段数据的类
class LineData {
    positions: THREE.Vector3[];
    constructor() {
        this.positions = [];
    }
    addPositions(positions: THREE.Vector3[]) {
        this.positions = this.positions.concat(positions);
    }
    slice(index: number, length: number) {
        return [...this.positions].slice(index, length)
    }
}



// 主逻辑类
export class DynamicLine {
    group: THREE.Group;
    maxLength: number
    index: number = 0
    allPoints: THREE.Vector3[] = []
    lineData: LineData
    line2Geometry: LineGeometry
    intervalTime: IntervalTime
    line2: Line2
    requestId: number = 0

    resMgr = new ResourceTracker();
    track
    checkGroup = new THREE.Group()

    constructor(group: THREE.Group, allPoints: THREE.Vector3[], checkGroup: THREE.Group, maxLength?: number) {
        this.checkGroup = checkGroup
        this.track = this.resMgr.track.bind(this.resMgr)
        this.maxLength = maxLength || 60
        this.group = group;
        this.allPoints = allPoints

        this.lineData = new LineData();
        this.lineData.addPositions(allPoints)

        this.line2Geometry = new LineGeometry();


        // 线的材质
        const radarLine2MatLine = new LineMaterial({
            linewidth: 0.003, // 可以调整线宽
            dashed: true,
            transparent: false,
            opacity: 0.5,
            color: 0x779a9f,
            vertexColors: false, // 是否使用顶点颜色
            fog: true
        });
        this.line2 = new Line2(this.line2Geometry, radarLine2MatLine);
        this.group.add(this.track(this.line2));

        this.intervalTime = new IntervalTime()

        this.upDate()
    }
    changeColor() {

    }
    upDate() {
        this.requestId = requestAnimationFrame(this.upDate.bind(this));
        if (this.index <= this.allPoints.length - this.maxLength) {
            const v3s = this.lineData.slice(this.index, this.index + this.maxLength);
            const arr = v3s.flatMap((v3) => v3.toArray());
            this.line2Geometry.setPositions(arr)
            this.index++
        } else {
            this.index = 0
            // this.resMgr.dispose();
            // cancelAnimationFrame(this.requestId)
        }
        this.checkGroup.children.forEach((car) => {
            const box3 = new THREE.Box3();

            box3.setFromObject(car);

            const lineBox3 = new THREE.Box3();
            lineBox3.setFromObject(this.line2);

            const isIntersects = box3.intersectsBox(lineBox3);
            
            if (isIntersects) {
                this.line2.material.color = new THREE.Color(0xff0000)
            } else {
                this.line2.material.color = new THREE.Color(0x779a9f)

            }

        })
    }
}
